package br.senai.sc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.senai.sc.connection.MySQLConn;
import br.senai.sc.entity.Aluno;
import br.senai.sc.entity.Login;

public class LoginDAO {

	public static Login findByNmLogin(String nmLogin) {

		Connection conn = MySQLConn.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Login login = null;

		try {
			ps = conn.prepareStatement("SELECT * FROM login WHERE nmLogin = '"
					+ nmLogin + "'");

			rs = ps.executeQuery();

			if (rs.next()) {
				login = createLogin(rs);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return login;
	}

	private static Login createLogin(ResultSet rs) throws SQLException {

		Login l = new Login();

		l.setId(rs.getInt("idlogin"));
		l.setNmLogin(rs.getString("nmlogin"));
		l.setSenha(rs.getString("senha"));

		return l;
	}

	public static void inserirLogin(Login login) {

		Connection conn = MySQLConn.getConn();
		PreparedStatement ps = null;

		try {

			ps = conn.prepareStatement("INSERT INTO login "
					+ "(nmlogin, senha) " + " VALUES (?, ?) ");

			ps.setString(1, login.getNmLogin());
			ps.setString(2, login.getSenha());

			ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			try {
				if (ps != null)
					ps.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

	}

	public static List<Login> getAll() {

		List<Login> logins = new ArrayList<Login>();

		Connection conn = MySQLConn.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(" SELECT * FROM login ");

			rs = ps.executeQuery();

			while (rs.next()) {

				Login login = new Login();

				login.setId(rs.getInt("idlogin"));
				login.setNmLogin(rs.getString("nmlogin"));
				login.setSenha(rs.getString("senha"));

				logins.add(login);

			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {

			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

		return logins;
	}

}
